package team526.controller;

//import com.sun.tracing.dtrace.ProviderAttributes;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import team526.vo.VO;
import team526.dao.UserDao;
import team526.dao.VideoDao;
import team526.entity.Favorite;
import team526.entity.History;
import team526.entity.User;
import team526.entity.Video;
import team526.service.UserService;

import javax.servlet.http.HttpSession;
//import javax.xml.soap.SAAJMetaFactory;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * #Date 2021/9/23 - 11:35
 *
 * @author 王铭 20181620310021
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("user")
@CrossOrigin(origins = {"http://localhost:8080","http://192.168.31.212:8080","http://127.0.0.1:8080","http://video.team526:8080"}, allowCredentials = "true")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    UserDao userDao;

    @Autowired
    VideoDao videoDao;

    /*@PostMapping("login")
    public BO<User> login(@RequestBody User user, HttpServletRequest request) {
        User user1 = userDao.login(user);
        if (user1 != null) {
            HttpSession session = request.getSession();
            String sessionKey = Long.toHexString(System.currentTimeMillis());
            session.setAttribute("sessionKey", sessionKey);
            return new BO<User>(user1, sessionKey, "login success");
        }
        return new BO<>(null, null, "用户名或密码不对");
    }

    @PostMapping("login_f")
    public BO<User> login_f(User user, HttpServletRequest request) {
        return login(user, request);
    }

    @GetMapping("check_name_if_used")
    public boolean check_name_if_used(String username) {
        if (userDao.search(username, null, null, null) == null)
            return false;
        return true;
    }


    @GetMapping("check_email_if_used")
    public boolean check_email_if_used(String email) {
        if (userDao.getByEmail(email) == null)
            return false;
        return true;
    }


    @PostMapping("sign")
    @ApiOperation("用户注册")
    public BO<User> sign(@RequestParam String email,
                         @RequestParam String info,
                         @RequestParam String username,
                         @RequestParam String password,
                         @RequestPart MultipartFile face_pic,
                         HttpServletRequest request) throws IOException {
        User user1 = userService.sign(email, info, username, password, face_pic);
        if (user1 != null) {
//            String pic_storage = savePic(face_pic);
//            user1.setFace(pic_storage);
//            userDao.updateUser(user1);
            HttpSession session = request.getSession();
            String sessionKey = Long.toHexString(System.currentTimeMillis());
            session.setAttribute("sessionKey", sessionKey);
            return new BO<User>(user1, sessionKey, "sign success");
        }
        return null;
    }*/

//    @RequestMapping("login")
//    public User login(User user, HttpSession session) {
//        //        code for login
//        session.setAttribute("currentUser", user);
//        session.setAttribute("sessionKey", "123");
//        return user;
//    }
    @ApiOperation(value = "用户注册", notes = "注册完成后自动登录")
    @PostMapping("register")
    public VO<User> register(@RequestBody User user,
                             @RequestPart(required = false) MultipartFile face_pic,
                             @ApiIgnore HttpSession session) throws IOException {
//        code for register
        return register_f(user.getEmail(), user.getInfo(), user.getName(), user.getPwd(), face_pic, session);
    }

    @ApiOperation(value = "用户注册，以表单形式提交", notes = "")
    @PostMapping("register_f")
    public VO<User> register_f(@RequestParam String email,
                               @RequestParam String info,
                               @RequestParam String username,
                               @RequestParam String password,
                               @RequestPart(required = false) MultipartFile face_pic,
                               @ApiIgnore HttpSession session) throws IOException {
//        code for register
        User user1 = userService.sign(email, info, username, password, face_pic);
        if (user1 != null)
            return login(user1, session);
        return null;
    }

    @ApiOperation("用户登录（表单提交）")
    @ApiImplicitParams({})
    @PostMapping("login_f")
    public VO<User> login_f(User user, @ApiIgnore HttpSession session) {
        return login(user, session);
    }

    @ApiOperation(value = "注销登录", notes = "")
    @GetMapping("logout")
    public String logout(@ApiIgnore HttpSession session) {
        session.invalidate();
        return "ok";
    }
    @ApiOperation(value = "注销账号", notes = "")
    @GetMapping("deleteAccount")
    public Integer deleteAccount(@RequestAttribute @ApiIgnore User currentUser, @ApiIgnore HttpSession session) {
        session.invalidate();
//        code for delete
        return userDao.deleteUser(currentUser.getUuid());
    }

    @ApiOperation(value = "获取当前登录的User", notes = "需要已登录会话")
    @GetMapping("getCurrent")
    public User getCurrent(@RequestAttribute @ApiIgnore User currentUser) {
        return currentUser;
    }


    @ApiOperation(value = "修改用户信息，未完成", notes = "")
    @PostMapping("change_info")
    public User change(@RequestParam String email,
                           @RequestParam String info,
                           @RequestParam String username,
                           @RequestParam String password,
                           @RequestPart(required = false) MultipartFile face,
                            @RequestAttribute@ApiIgnore User currentUser) throws IOException {
        return userService.changeInfo(username,password,email,info,face,currentUser);
    }

    @ApiOperation(value = "通过uuid获取用户信息", notes = "")
    @GetMapping("info/{uuid}")
    public User info(@PathVariable Integer uuid) {
        return userDao.getUserInfo(uuid);
    }

    @GetMapping("check_name_if_used")
    public boolean check_name_if_used(String username) {
        if (userDao.getByName(username) == null)
            return false;
        return true;
    }

    @ApiOperation(value = "检查email是否已被注册", notes = "")
    @GetMapping("check_email_if_used")
    public boolean check_email_if_used(String email) {
        if (userDao.getByEmail(email) == null)
            return false;
        return true;
    }

    @ApiOperation(value = "用户登录", notes = "")
    @PostMapping("login")
    public VO<User> login(@RequestBody User user, @ApiIgnore HttpSession session) {
        User user1 = userDao.login(user);
        if (user1 != null) {
            String sessionKey = Long.toHexString(System.currentTimeMillis());
            session.setAttribute("sessionKey", sessionKey);
            session.setAttribute("currentUser", user1);
            return new VO<User>(user1, sessionKey, "登录成功");
        }
        session.invalidate();
        return new VO<>(null, null, "用户名或密码错误");
    }


    //订阅接口
    @ApiOperation(value = "关注某个用户", notes = "需要登录")
    @GetMapping("subscribeAUser/{uuid}")
    public Integer subscribeAUser(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer uuid) {
//        code for sub
        return userDao.subs(currentUser.getUuid(), uuid);
    }

    @ApiOperation(value = "取消关注某一个用户", notes = "需要登录")
    @GetMapping("cancelSub/{uuid}")
    public Integer cancelSub(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer uuid) {
        return userDao.cancelSub(currentUser.getUuid(), uuid);
    }

    @ApiOperation(value = "获得当前用户的关注列表", notes = "")
    @GetMapping("getSubs")
    public PageInfo<User> getSubs(@RequestAttribute @ApiIgnore User currentUser,Integer page,Integer num) {
//        return userDao.getSubs(currentUser.getUuid(),(page-1)*num,num);
        return PageHelper.startPage(page,num).doSelectPageInfo(()->userDao.getSubs(currentUser.getUuid(),null,null));
    }

    @ApiOperation(value = "检查是否关注了这个用户", notes = "")
    @GetMapping("ifSub/{suid}")
    public boolean ifSub(@RequestAttribute @ApiIgnore User currentUser,@PathVariable Integer suid){
        Object o = userDao.ifSub(currentUser.getUuid(), suid);
        if (o!=null)
            return true;
        return false;
    }

    //点赞接口
    @ApiOperation(value = "点赞某个视频", notes = "")
    @GetMapping("likeVideo/{videoid}")
    public Integer likeVideo(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer videoid) {
        return userDao.likeVideo(currentUser.getUuid(), videoid);
    }

    @ApiOperation(value = "取消点赞某个视频", notes = "")
    @GetMapping("unlikeVideo/{videoid}")
    public Integer unlikeVideo(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer videoid) {
        return userDao.unlikeVideo(currentUser.getUuid(), videoid);
    }


    @ApiOperation(value = "检查是否点赞了这个视频", notes = "")
    @GetMapping("ifLike/{videoid}")
    public boolean getLike(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer videoid) {
        Object o = userDao.getLike(currentUser.getUuid(), videoid);
        if (o!=null)
            return true;
        return false;
    }

    //搜藏夹管理
    @ApiOperation(value = "收藏某个视频", notes = "")
    @GetMapping("favorite")
    public Integer favorite(@RequestAttribute @ApiIgnore User currentUser, Integer videoid) {
        return userDao.favorite(currentUser.getUuid(), videoid, new Date());
    }

    @ApiOperation(value = "获取收藏列表", notes = "")
    @GetMapping("getFavorite/{page}")
    public PageInfo<Favorite> getFavorite(@RequestAttribute @ApiIgnore User currentUser,@PathVariable(required = false)Integer page) {
        return PageHelper.startPage(page,10).doSelectPageInfo(()->userDao.getFavorite(currentUser.getUuid()));
    }

    @ApiOperation(value = "检查是否收藏了这个视频", notes = "")
    @GetMapping("ifFavorite/{videoid}")
    public boolean ifFavorite(@RequestAttribute @ApiIgnore User currentUser, @PathVariable Integer videoid){
        Object o = userDao.ifFavorite(currentUser.getUuid(), videoid);
        if (o!=null)
            return true;
        return false;
    }

    @ApiOperation(value = "取消收藏某个视频", notes = "")
    @GetMapping("deleteF")
    public Integer deleteF(@RequestAttribute @ApiIgnore User currentUser,@RequestParam(value = "videoIds",required = false) List<Integer> videoIds) {
        return userDao.deleteFbyVideoId(currentUser.getUuid(),videoIds);
    }

    //    历史记录管理
    @ApiOperation(value = "获取历史记录", notes = "需要登录")
    @GetMapping("getHistory/{page}")
    public PageInfo<History> getHistory(@RequestAttribute @ApiIgnore User currentUser,@PathVariable(required = false)Integer page) {
        return PageHelper.startPage(page,10).doSelectPageInfo(()->userDao.getHistory(currentUser.getUuid()));
    }

    @ApiOperation(value = "删除某个历史记录", notes = "")
    @GetMapping("deleteH")
    public Integer deleteH(@RequestAttribute @ApiIgnore User currentUser, @RequestParam(value = "videoIds")List<Integer> videoIds) {
        return userDao.deleteHbyPk(videoIds,currentUser.getUuid());
    }

    @ApiOperation(value = "插入一个历史记录", notes = "")
    @GetMapping("saveOrUpdateHistory")
    public Integer saveHistory(@RequestAttribute @ApiIgnore User currentUser, Integer videoid, @RequestParam(required = false) Integer watch_to) {
        return userService.saveOrUpdateH(currentUser.getUuid(), videoid, watch_to);
    }

    //    个人视频管理
    @ApiOperation(value = "获得某人的视频列表", notes = "不需要登录")
    @GetMapping("getVideoRepository")
    public PageInfo<Video> getVideoRepository(Integer uuid, Integer page, Integer num) {
        return PageHelper.startPage(page,num).doSelectPageInfo(()->videoDao.getVideosByUuid(uuid,null,null));
    }

    @ApiOperation(value = "删除视频", notes = "")
    @GetMapping("deleteVideoRepository")
    public Integer deleteVideoRepository(@RequestParam List<Integer> videoIds,@RequestAttribute@ApiIgnore User currentUser) {
        return userDao.deleteList(videoIds,currentUser.getUuid());
    }

    @ApiOperation(value = "管理视频列表")
    @GetMapping("videoListToManage")
    public PageInfo<Video> manage(Integer status,Integer page,Integer num,@RequestAttribute @ApiIgnore User currentUser ){
        return PageHelper.startPage(page,num).doSelectPageInfo(()->userDao.getManageList(currentUser.getUuid(),status));
    }
//发布视频


}
